/**
 * User: Clinton Begin Date: Jul 13, 2003 Time: 7:21:08 PM
 */
package com.alibaba.sample.petstore.dal.dao.ibatis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.alibaba.sample.petstore.dal.dao.ItemDao;
import com.alibaba.sample.petstore.dal.dataobject.Item;
import com.alibaba.sample.petstore.dal.dataobject.LineItem;
import com.alibaba.sample.petstore.dal.dataobject.Order;

public class IbatisItemDao extends SqlMapClientDaoSupport implements ItemDao {
    public void updateQuantity(Order order) {
        for (int i = 0; i < order.getLineItems().size(); i++) {
            LineItem lineItem = (LineItem) order.getLineItems().get(i);
            String itemId = lineItem.getItemId();
            Integer increment = new Integer(lineItem.getQuantity());
            Map param = new HashMap(2);

            param.put("itemId", itemId);
            param.put("increment", increment);
            getSqlMapClientTemplate().update("updateInventoryQuantity", param);
        }
    }

    public boolean isItemInStock(String itemId) {
        Integer i = (Integer) getSqlMapClientTemplate().queryForObject("getInventoryQuantity", itemId);

        return i != null && i.intValue() > 0;
    }

    public List getItemListByProductId(String productId) {
        return getSqlMapClientTemplate().queryForList("getItemListByProduct", productId);
    }

    public Item getItemById(String itemId) {
        Integer i = (Integer) getSqlMapClientTemplate().queryForObject("getInventoryQuantity", itemId);
        Item item = (Item) getSqlMapClientTemplate().queryForObject("getItem", itemId);

        if (item != null && i != null) {
            item.setQuantity(i.intValue());
        }

        return item;
    }
}
